package com.example.demo.socket;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.awt.*;

public class GameWebSocketHandler extends TextWebSocketHandler {
    private final FiveGameService gameService = new FiveGameService();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        sendState(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        String input = message.getPayload();
        if ("RESET".equalsIgnoreCase(input)) {
            gameService.reset();
        } else {
            try {
                String[] parts = input.split(",");
                int x = Integer.parseInt(parts[0]);
                int y = Integer.parseInt(parts[1]);
                gameService.changeDirection(new Point(x, y));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        sendState(session);
    }

    private void sendState(WebSocketSession session) {
        try {
            String json = objectMapper.writeValueAsString(gameService.getState());
            session.sendMessage(new TextMessage(json));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
